<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="选择品种" prop="plantVarietyId">
                <el-select v-model="ruleForm.plantVarietyId" class="w100p" filterable placeholder="请选择养殖品种"
                    @change="handleChangePlantVariety">
                    <el-option v-for="item, index in varietyList" :key="index" :label="item.plantVarietyName"
                        :value="item.plantVarietyId"></el-option>
                </el-select>
            </el-form-item>
            <el-row v-if="addEditFlag == 'add'" v-for="item, index in ruleForm.growFeedList" :key="index">
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '选择阶段' : ''" :prop="`growFeedList[${index}][growStageId]`"
                        :rules="rules.growStageId">
                        <el-select v-model="item.growStageId" class="w100p" filterable placeholder="请选择阶段">
                            <el-option v-if="ruleForm.plantVarietyId == item.plantVarietyId"
                                v-for="item, index in growthStageList" :key="index" :label="item.growStageName"
                                :value="item.growStageId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '日投喂次数' : ''" :prop="`growFeedList[${index}][num]`"
                        :rules="rules.num">
                        <el-input type="number" v-model="item.num" placeholder="请输入次数">
                            <template slot="append">次</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
            <el-row v-if="addEditFlag == 'edit'">
                <el-col :span="12">
                    <el-form-item label="选择阶段" prop="growStageId">
                        <el-select v-model="ruleForm.growStageId" class="w100p" filterable placeholder="请选择阶段">
                            <el-option v-if="ruleForm.plantVarietyId == item.plantVarietyId"
                                v-for="item, index in growthStageList" :key="index" :label="item.growStageName"
                                :value="item.growStageId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="日投喂次数" prop="num">
                        <el-input type="number" v-model="ruleForm.num" placeholder="请输入次数">
                            <template slot="append">次</template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="投喂建议">
                <el-input v-model="ruleForm.remark" placeholder="请输入投喂建议"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import growFeedConfig from '@/api/cropModel/growFeedConfig'
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        varietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        growthStageList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数！'))
            }
        }
        return {
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                growStageId: [
                    { required: true, message: '请选择阶段', trigger: 'change' }
                ],
                plantVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
            }
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                if (this.ruleForm.growFeedList && Array.isArray(this.ruleForm.growFeedList)) {
                    this.$set(this.ruleForm.growFeedList, 0, {
                        plantVarietyName: null, num: null, plantVarietyId: null
                    });
                } else {
                    this.$set(this.ruleForm, 'growFeedList', [{
                        plantVarietyName: null, num: null, plantVarietyId: null
                    }])
                };
                this.addEditApi = growFeedConfig.addList;
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data };
                this.addEditApi = growFeedConfig.edit;
                this.addEditName = '编辑';
            }
        },
        addMaterial() {
            let length = this.ruleForm.growFeedList?.length || 0
            if (length) {
                this.$set(this.ruleForm.growFeedList, length, {
                    plantVarietyName: null, num: null, plantVarietyId: null
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.growFeedList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'growFeedList', list)
        },
        isHasGrowStage(id) {
            if (!id) return;
            let chooseGrowStage = this.growthStageList.filter(item => {
                return id == item.plantVarietyId
            })
            if (chooseGrowStage.length == 0) {
                this.$message.warning('该品种未配置阶段')
            }
        },
        handleChangePlantVariety(id) {
            if (this.addEditFlag == 'add') {
                let growFeedList = this.ruleForm.growFeedList;
                growFeedList.forEach((item, index) => {
                    item.growStageId = ''
                    this.$set(this.ruleForm.growFeedList, index, {
                        plantVarietyName: null, num: null, plantVarietyId: null
                    })
                })
            } else if (this.addEditFlag = 'edit') {
                this.$set(this.ruleForm, 'growStageId', '')
            }
        },
        getPlantVariety(id) {
            let plantVarietyName = this.$public.foundObject(this.varietyList, 'plantVarietyId', id).plantVarietyName || '';
            return plantVarietyName
        },
        handleChangeGrowthStageName(id) {
            let growStageName = this.$public.foundObject(this.growthStageList, 'growStageId', id).growStageName || '';
            return growStageName
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let params = null
                    if (this.addEditFlag == 'add') {
                        params = []
                        this.ruleForm.growFeedList.forEach(item => {
                            console.log(item)
                            params.push({
                                ...item,
                                plantVarietyId: this.ruleForm.plantVarietyId,
                                plantVarietyName: this.getPlantVariety(this.ruleForm.plantVarietyId),
                                growStageName: this.handleChangeGrowthStageName(item.growStageId)
                            })
                        });
                    } else {
                        params = {
                            ...this.ruleForm,
                            plantVarietyName: this.getPlantVariety(this.ruleForm.plantVarietyId),
                            growStageName: this.handleChangeGrowthStageName(this.ruleForm.growStageId)
                        }
                    }

                    this.addEditApi(params).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}
</style>